package com.yuantong.xyerp;

import apijson.StringUtil;
import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONCreator;
import apijson.orm.*;
import com.yuantong.xyerp.rest.config.APIJson.*;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.regex.Pattern;

@SpringBootApplication
@MapperScan("com.yuantong.xyerp.core.provider.dao")
public class XyerpRestApplication implements ApplicationContextAware {


    private static final Logger logger = LoggerFactory.getLogger(XyerpRestApplication.class);
    public static void main(String[] args) throws Exception {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        SpringApplication.run(XyerpRestApplication.class, args);

        APIJSONApplication.init(false); // 4.4.0 以上需要这句来保证以上 static 代码块中给 DEFAULT_APIJSON_CREATOR 赋值会生效
        logger.info("\n\n=== xyerp system start success ===\n");

    }

    static {
        // APIJSON 配置 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        /**
         * AbstractVerifier.COMPILE_MAP 用来校检数据格式的, 这里保留一个做参考
         */
        Map<String, Pattern> COMPILE_MAP = AbstractVerifier.COMPILE_MAP;
        COMPILE_MAP.put("PHONE", StringUtil.PATTERN_PHONE);

        // 使用本项目的自定义处理类
        APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator() {
            @Override
            public SQLConfig createSQLConfig() {
                return new XyerpSQLConfig();
            }
            @Override
            public SQLExecutor createSQLExecutor() {
                return new XyerpSQLExecutor();
            }
            @Override
            public FunctionParser createFunctionParser() {
                return new XyerpFunctionParser();
            }
            @Override
            public Parser<Long> createParser() {
                return new XyerpParser();
            }
        };
    }

    // 全局 ApplicationContext 实例，方便 getBean 拿到 Spring/SpringBoot 注入的类实例
    private static ApplicationContext APPLICATION_CONTEXT;

    @Resource
    private JdbcTemplate jdbcTemplate;


    public static ApplicationContext getApplicationContext() {


        return APPLICATION_CONTEXT;
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
    }

}
